//创建和更新记录
//1. 以openid 为用户id来添加更新删除数据(更改同一条数据)
//2. 包含所有邮卡、更新时间、随机奖品

// 云函数入口文件


const cloud = require('wx-server-sdk')

cloud.init()
// var num = 0;

const db= cloud.database();
const col = db.collection('jiyou');
const _=db.command;
// 云函数入口函数
exports.main = async (event, context) => {
  // console.log(event);
  const wxContext = cloud.getWXContext()
  var rand = Math.random();
  let type;
  switch (true) {
    case (rand < 0.3):
      type = 0;
      break;
    case (rand < 0.6 && rand >= 0.3):
      type = 1;
      break;
    case (rand < 0.9 && rand >= 0.6):
      type = 2;
      break;
    case (rand >= 0.9):
      type = 3;
      break;
  }
  let words = [
    { name: '邮家贷', type: '0', number: 0 },
    { name: '邮学贷', type: '1', number: 0 },
    { name: '邮薪贷', type: '2', number: 0 },
    { name: '邮掌柜', type: '3', number: 0 }
  ]
  //查询数据库在数据库中的记录
   var user = await col.where({
     '_openid': wxContext.OPENID
   }).get();
  
   if(user.data.length === 0){
    //  num++;
    //  console.log('user', user.data)
     
     words[type].number += 1;
     let data = {
       '_openid': wxContext.OPENID,
       'words': words,
       updataTime: getDay(),
       time: 1,
       prize: null
     }
     let result = await col.add({
       data: data
     })
     return {
       msg: '添加成功',
       result: result,
       user:user,
       type
      //  user:user

     }
    //  console.log(user.data.length)
    }
    else{
     //除第一次外都是更新操作
    user = user.data[0];
    if(user.time == 0&&user.updataTime == getDay()){
      return{
        msg:'今天次数用完',
        success:false,
      }
    }
    //time代表剩余次数，在第二天是重置
    let time;
     if (user.updataTime !== getDay()){
        time = 2;
     }
    // 增加一个
    user.words[type].number+=1;

    let result = await col.where({
      '_openid':wxContext.OPENID
    }).update({
      data:{
         words:user.words,
         'updataTime':getDay(),
         'time':time || _.inc(-1),
      }
    });
     return {
       msg: '修改成功',
      //  result: result,
       user: user,
       event:event,
       type
     } 
  //  }
 // 随机邮字
  
}




}
function getDay() {
  let d = new Date();
  return d.getFullYear() + '-' + d.getMonth() + 1 + '-' + d.getDate();
}